import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import('../components/Login') }, //路由懒加载
  {
    path: '/home',
    component: () => import('../components/Home'),
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: () => import('../components/Welcome') },
      { path: '/users', component: () => import('../components/user/Users') },
      {
        path: '/rights',
        component: () => import('../components/power/Rights')
      },
      { path: '/roles', component: () => import('../components/power/Roles') },
      {
        path: '/categories',
        component: () => import('../components/goods/Cate')
      },
      {
        path: '/params',
        component: () => import('../components/goods/Params')
      },
      {
        path: '/goods',
        component: () => import('../components/goods/List')
      },
      {
        path: '/goods/add',
        component: () => import('../components/goods/AddGoods')
      },
      {
        path: '/orders',
        component: () => import('../components/order/Order')
      },
      {
        path: '/reports',
        component: () => import('../components/report/Report')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
//全局前置路由守卫
router.beforeEach((to, from, next) => {
  //判断要去的页面是否是登录页，是的话直接放行
  if (to.path === '/login') return next()
  //去除了登陆组件的其他页面，需要判断是否有token权限
  const token = window.sessionStorage.getItem('token')
  //如果没有，路由会跳转到登陆页面
  if (!token) return next('/login')
  //有就直接放行
  next()
})

export default router
